<template>
  <div class="qa-editor" :style="editorStyle">
      <template v-if="!readOnly && !hideToolBar">
          <Toolbar
              class="qa-editor__toolbar"
              :editor="editor"
              :defaultConfig="toolbarConfig"
          />
      </template>
      <Editor
          class="qa-editor__editor"
          :value="value"
          mode="simple"
          :readOnly="readOnly"
          :defaultHtml="defaultValue"
          :defaultConfig="editorConfig"
          :maxlength="parseLimit"
          @onCreated="onCreated"
          @onChange="onChange"
          @onDestroyed="onDestroyed"
          @onFocus="onFocus"
          @onBlur="onBlur"
          @customAlert="customAlert"
          @customPaste="customPaste"
      />
  </div>
</template>

<script>
// import { SlateEditor } from '@wangeditor/editor';
const { SlateEditor } = window.wangEditor
import Toolbar from '@/components/QaEditor/components/Toolbar';
import Editor from '@/components/QaEditor/components/Editor';
import { cos, wordCounter, checkImageResolution } from '@/utils'; // , extractTextFromHtml, subStrWordCount
import { SYS_COS_PREFIX, mimeToExtension, COS_BIZ_TYPE } from '@/constants';

export default {
  name: 'QaEditor',
  components: {
      Toolbar,
      Editor
  },
  props: {
      parseLimit: {
          type: Number,
          default: 12000
      },
      value: {
          type: String,
          default: ''
      },
      acceptImgType: {
          type: String,
          default: ''
      },
      hideToolBar: {
          type: Boolean,
          default: false
      },
      disabled: {
          type: Boolean,
          default: false
      },
      // 是否只读
      readOnly: {
          type: Boolean,
          default: false
      },
      placeholder: {
          type: String,
          default: '请输入你的问题，支持上传图片或文件。'
      },
      editorStyle: {
          type: String,
          default: ''
      },
      defaultValue: {
          type: String,
          default: ''
      }
  },
  data () {
      return {
          editor: null,
          toolbarConfig: {
              // 包含的工具
              toolbarKeys: [
                  /* 'blockquote',
                  'bold',
                  'underline',
                  'italic',
                  'color',
                  'bgColor',
                  'fontSize',
                  'fontFamily',
                  'bulletedList',
                  'numberedList',
                  'group-justify',
                  'group-indent',
                  'insertTable',
                  'divider', */

                  'emotion',
                  {
                      key: 'group-image',
                      title: '图片', // 必填
                      iconSvg: '<svg width="12" height="10" viewBox="0 0 12 10" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M2.03317 1.20825C1.69203 1.20825 1.48881 1.20893 1.33816 1.22124C1.24622 1.22875 1.20757 1.23867 1.19721 1.24188C1.14513 1.26932 1.10257 1.31188 1.07513 1.36396C1.07192 1.37432 1.062 1.41296 1.05449 1.50491C1.04218 1.65556 1.0415 1.85878 1.0415 2.19992V6.41081L2.75328 4.45363L3.0825 4.07722L3.41183 4.45354L4.66141 5.8814L7.26909 3.17141L7.58767 2.84033L7.90276 3.17474L10.9582 6.41747V2.19992C10.9582 1.85878 10.9575 1.65556 10.9452 1.50491C10.9377 1.41297 10.9278 1.37432 10.9245 1.36396C10.8971 1.31188 10.8545 1.26932 10.8025 1.24188C10.7921 1.23867 10.7535 1.22875 10.6615 1.22124C10.5109 1.20893 10.3076 1.20825 9.9665 1.20825H2.03317ZM1.0415 7.73024V7.79992C1.0415 8.14105 1.04218 8.34428 1.05449 8.49493C1.062 8.58687 1.07192 8.62552 1.07513 8.63588C1.10257 8.68796 1.14513 8.73052 1.19721 8.75796C1.20757 8.76117 1.24622 8.77109 1.33816 8.7786C1.48881 8.79091 1.69204 8.79159 2.03317 8.79159H9.9665C10.3076 8.79159 10.5109 8.79091 10.6615 8.7786C10.7535 8.77108 10.7921 8.76117 10.8025 8.75796C10.8545 8.73052 10.8971 8.68796 10.9245 8.63588C10.9278 8.62552 10.9377 8.58687 10.9452 8.49493C10.9575 8.34428 10.9582 8.14105 10.9582 7.79992V7.671L10.4114 7.113L10.4084 7.10994L10.4055 7.10683L7.58101 4.1092L4.96137 6.83161L4.63084 7.17512L4.31689 6.81638L3.0827 5.4061L1.62107 7.07726L1.61897 7.07966L1.61896 7.07965L1.0415 7.73024ZM10.8055 1.24293L10.8037 1.24228C10.805 1.24269 10.8055 1.24292 10.8055 1.24293ZM10.9235 1.36094C10.9235 1.36091 10.9237 1.36145 10.9241 1.36269L10.9235 1.36094ZM10.9235 8.6389L10.9241 8.63715C10.9237 8.63841 10.9235 8.63895 10.9235 8.6389ZM10.8055 8.7569C10.8055 8.75691 10.805 8.75714 10.8037 8.75755L10.8055 8.7569ZM1.19419 8.7569L1.19596 8.75756C1.19471 8.75715 1.19416 8.75692 1.19419 8.7569ZM1.07619 8.6389C1.07617 8.63893 1.07594 8.63838 1.07553 8.63713L1.07619 8.6389ZM1.07619 1.36094L1.07553 1.36271C1.07594 1.36146 1.07617 1.36091 1.07619 1.36094ZM1.19419 1.24293C1.19416 1.24292 1.19471 1.24269 1.19596 1.24228L1.19419 1.24293ZM0.166504 2.19992C0.166504 1.54652 0.166504 1.21983 0.293663 0.970263C0.405515 0.750741 0.583993 0.572263 0.803515 0.460411C1.05308 0.333252 1.37978 0.333252 2.03317 0.333252H9.9665C10.6199 0.333252 10.9466 0.333252 11.1962 0.460411C11.4157 0.572263 11.5942 0.750741 11.706 0.970263C11.8332 1.21983 11.8332 1.54652 11.8332 2.19992V7.79992C11.8332 8.45331 11.8332 8.78001 11.706 9.02957C11.5942 9.2491 11.4157 9.42757 11.1962 9.53943C10.9466 9.66659 10.6199 9.66659 9.9665 9.66659H2.03317C1.37978 9.66659 1.05308 9.66659 0.803515 9.53943C0.583993 9.42757 0.405515 9.2491 0.293663 9.02957C0.166504 8.78001 0.166504 8.45331 0.166504 7.79992V2.19992Z" fill="#00010A" fill-opacity="0.93"/></svg>',
                      menuKeys: [
                          'uploadImage',
                          'insertImage'
                      ]
                  },
                  'insertLink'
              ]
              // 排除的工具
              /* excludeKeys: [
                  'undo',
                  'redo',
                  'todo',
                  'fullScreen',
                  'group-video'
              ] */
          },
          editorConfig: {
              readOnly: this.readOnly || this.disabled,
              placeholder: this.readOnly ? '' : this.placeholder,
              hoverbarKeys: {
                  'link': {
                      'menuKeys': [
                          'editLink',
                          'unLink'
                      ]
                  },
                  'image': {
                      'menuKeys': [
                      ]
                  },
                  'pre': {
                      'menuKeys': [
                          'enter',
                          'codeBlock',
                          'codeSelectLang'
                      ]
                  },
                  'table': {
                      'menuKeys': [
                          'enter',
                          'tableHeader',
                          'tableFullWidth',
                          'insertTableRow',
                          'deleteTableRow',
                          'insertTableCol',
                          'deleteTableCol',
                          'deleteTable'
                      ]
                  },
                  'divider': {
                      'menuKeys': [
                          'enter'
                      ]
                  },
                  'video': {
                      'menuKeys': [
                          'enter',
                          'editVideoSize'
                      ]
                  }
              },
              MENU_CONF: {
                  insertLink: {
                      checkLink: this.checkLink
                  },
                  uploadImage: { // 自定义上传图片
                      customUpload: this.customUpload,
                      // 自定义插入图片 方法
                      customInsert: this.customInsert
                      // customInsert: this.customInsert,
                      // onBeforeUpload: this.onBeforeUpload,
                      // onProgress: this.onProgress,
                      // onSuccess: this.onSuccess,
                      // onFailed: this.onFailed,
                      // onError: this.onError

                  },
                  insertImage: {
                      checkImage: this.checkImage,
                      parseImageSrc: async (src) => {
                          console.log('parseImageSrc');
                          if (SYS_COS_PREFIX.find(str => src.indexOf(str) > -1)) {
                              console.log('finded', src);
                              return src;
                          } else {
                              const that = this;
                              console.log('uploadImg', src);
                              return new Promise((resolve, reject) => {
                                  let image = new Image();
                                  // 解决跨域 Canvas 污染问题
                                  image.setAttribute('crossOrigin', 'anonymous');
                                  image.onload = function () {
                                      if (image.width > 2000 || image.height > 2000) {
                                          this.$message.error('图片长或宽不能超过2000，请重新选择');
                                          return;
                                      }
                                      let canvas = document.createElement('canvas');
                                      canvas.width = image.width;
                                      canvas.height = image.height;
                                      let context = canvas.getContext('2d');
                                      context.drawImage(image, 0, 0, image.width, image.height);
                                      let url = canvas.toDataURL('image/png'); // 得到图片的base64编码数据
                                      const saveName = cos.reNameFile(20) + '.png';
                                      const file = that.dataURLtoBlob(url);
                                      const fileItem = {
                                          saveName: saveName,
                                          name: saveName,
                                          data: file,
                                          type: 'image/png'
                                      };
                                      cos.upload(false, COS_BIZ_TYPE.DOC_UPLOAD, [fileItem]).then((res) => {
                                          resolve(res.url);
                                      });
                                  };
                                  image.src = src;
                                  image.onerror = () => {
                                      this.$message.error('当前链接的图片无法获取到，请下载到本地后在上传。');
                                      reject(new Error(`Failed to load image`));
                                  };
                              });
                          }
                      }, // 也支持 async 函数
                      onInsertedImage: (imageNode) => {
                          if (imageNode == null) return;
                          const { src, alt, url, href } = imageNode;
                          console.log('inserted image', src, alt, url, href);
                      }
                  }
              }
          }
      };
  },
  created () {

  },
  computed: {
      wordCount () {
          return wordCounter(this.value);
      }
  },
  mounted () {

  },
  methods: {
      checkFileType (file, acceptType) {
          const allowedExtensions = acceptType.split(',');

          // 获取文件扩展名
          const fileExtension = '.' + file.name.split('.').pop().toLowerCase();

          // 检查文件扩展名是否在允许的扩展名列表中
          if (!allowedExtensions.includes(fileExtension)) {
              this.$message.error('不允许的文件类型！');
              return false;
          }
          return true;
      },
      lastSelection () {
          if (this.editor) {
              const endPoint = SlateEditor.end(this.editor, []);
              this.editor.select(endPoint);
          }
      },
      getEditorValue () {
          return this.editor.getHtml();
      },
      onChange (editorHtml) {
          this.$emit('input', editorHtml);
      },
      onCreated (editor) {
          this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
          // console.log('== 编辑器配置 ==', this.editor.getConfig().MENU_CONF)
      },
      // 自定义插入图片
      customInsert (file) {
          console.log(file);
      },
      // 自定义上传
      customUpload (file, insertFn) {
          console.log('customUpload');
          if (!this.checkFileType(file, this.acceptImgType)) return;
          // 显示图片大小
          if (file.size > 20 * 1024 * 1024) {
              this.$message.error('图片大小不能超过20MB，请重新选择');
              return;
          }
          if (file.size <= 0) {
              this.$message.error('图片大小应大于0MB，请重新选择');
              return;
          }

          let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
          let saveName = cos.reNameFile(20) + '.' + fileType;
          const fileList = [{
              saveName: saveName,
              name: file.name,
              data: file
          }];
          checkImageResolution(file).then(() => {
          // cos上传图片进度
          // const onUploadCosProgress = () => {};
              cos.upload(false, COS_BIZ_TYPE.DOC_UPLOAD, fileList).then((res) => {
                  insertFn(res.url, file.name, res.url); // 上传成功后，插入图片
              });
          }).catch(() => {
              this.$message.error('图片长或宽不能超过2000，请重新选择');
          });
          // cos.upload(fileList, onUploadCosProgress, afterUploadCos, true); // cos.upload 上传size限制5M
      },
      onDestroyed (editor) {
          // console.log('onDestroyed', editor);
      },
      onFocus (editor) {
          this.$emit('focus');
          // console.log('onFocus', editor);
      },
      onBlur (editor) {
          this.$emit('blur');
          // console.log('onBlur', editor);
      },
      customAlert (info, type) {
          this.$message.error(`${type}:\n${info}`);
      },
      customPaste (editor, event, cb) {
          console.log('customPaste');
          // console.log('ClipboardEvent 粘贴事件对象', event);
          // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
          const text = event.clipboardData.getData('text/plain'); // 获取粘贴的纯文本
          // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）
          console.log('customPaste', text);
          // 没有文本的情况下，判断是否有图片文件，有的话上传图片并贴图片进去
          if (!text) {
              return true;
          }
          // 自定义插入内容
          if (text.length > this.parseLimit) {
              editor.insertText(text.substr(0, this.parseLimit));
              this.$message.warning(`当前粘贴内容（包含格式）超过${this.parseLimit}字符，将截取纯文本的前${this.parseLimit}个字符进行粘贴`);

          // const pureText = extractTextFromHtml(text);
          // if (this.wordCount + pureText.length > this.parseLimit) {
          //     let curText = editor.getHtml() + pureText;
          //     editor.clear();
          //     editor.dangerouslyInsertHtml(subStrWordCount(curText, this.parseLimit));
          //     this.$message.warning(`当前内容超过${this.parseLimit}字符，将截取纯文本的前${this.parseLimit}个字符`);
          } else {
              editor.insertText(text);
          }
          // 返回 false ，阻止默认粘贴行为
          event.preventDefault();
          // eslint-disable-next-line standard/no-callback-literal
          cb && cb(false); // 返回值（注意，vue 事件的返回值，不能用 return）
          // } else {
          //     let html = event.clipboardData.getData('text/html'); // 获取粘贴的 html
          //     // let text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
          //     let rtf = event.clipboardData.getData('text/rtf'); // 获取 rtf 数据（如从 word wsp 复制粘贴）
          //     console.log('html', 'rtf', rtf);
          //     if (html && rtf) {
          //         // 列表缩进会超出边框，直接过滤掉
          //         // eslint-disable-next-line no-useless-escape
          //         html = html.replace(/text\-indent:\-(.*?)pt/gi, '');

          //         // 从html内容中查找粘贴内容中是否有图片元素，并返回img标签的属性src值的集合
          //         const imgSrcs = this.findAllImgSrcsFromHtml(html);

          //         // 如果有
          //         if (imgSrcs && Array.isArray(imgSrcs) && imgSrcs.length) {
          //         // 从rtf内容中查找图片数据
          //             const rtfImageData = this.extractImageDataFromRtf(rtf);

          //             // 如果找到
          //             if (rtfImageData.length) {
          //                 const imgCosUrls = [];
          //                 const finishedUpload = () => {
          //                     html = html.replace(/<!--(.*?)-->/gi, '');
          //                     html = html.replace(/<link(.*?)>/gi, '');
          //                     html = html.replace(/<meta(.*?)>/gi, '');
          //                     html = html.replace(/<html(.*?)>/gi, '<html>');
          //                     html = html.replace(/<style>(.*?)<\style>/gi, '');
          //                     html = html.replace(/<xml>(.*?)<\/xml>/gi, '');
          //                     html = html.replace(/<xml>[\s\S]*?<\/xml>/ig, '');
          //                     html = html.replace('/(\\n|\\r| class=(")?Mso[a-zA-Z]+(")?)/g', '');
          //                     let reg = new RegExp('<!--(.*?)-->', 'g');
          //                     html = html.replace(reg, '');
          //                     const regex1 = /<v:[^>]+>[\s\S]*?<\/v:[^>]+>/g;
          //                     html = html.replace(regex1, '');
          //                     const regex2 = /<o:[^>]+>[\s\S]*?<\/o:[^>]+>/g;
          //                     html = html.replace(regex2, '');

          //                     const cancelWordStyle = (str2, word1, word2) => {
          //                         if (str2.includes(word1)) {
          //                             str2 = str2.replace(word1, '');
          //                             str2 = str2.replace(word2, '');

          //                             if (str2.includes(word1)) {
          //                                 str2 = cancelWordStyle(str2, word1, word2);
          //                                 return str2;
          //                             } else return str2;
          //                         } else return str2;
          //                     };
          //                     // 去除original_content文本里的多余代码
          //                     let word1 = '<!--[if gte mso 9]>';
          //                     let word2 = '<!--[if gte mso 10]>';
          //                     let word4 = '<![if !vml]>';
          //                     let word5 = '<!--[if gte vml 1]>';
          //                     let word6 = '<!--[if !mso]>';
          //                     let word7 = '<![endif]>';
          //                     let word3 = '<![endif]-->';
          //                     if (html.includes(word1)) {
          //                         html = cancelWordStyle(html, word1, word3);
          //                     }
          //                     if (html.includes(word2)) {
          //                         html = cancelWordStyle(html, word2, word3);
          //                     }
          //                     if (html.includes(word4)) {
          //                         html = cancelWordStyle(html, word4, word7);
          //                     }
          //                     if (html.includes(word5)) {
          //                         html = cancelWordStyle(html, word5, word3);
          //                     }
          //                     if (html.includes(word6)) {
          //                         html = cancelWordStyle(html, word6, word3);
          //                     }

          //                     // const regex3 = /<span[^>]*>((?:.|\n)*?<img[^>]+>(?:.|\n)*?)<\/span>/g;
          //                     // html = html.replace(regex3, '<p>$1</p>');
          //                     const replaceSpanWithP = (xmlString) => {
          //                         const regex = /<span[^>]*>((?:\s*<img[^>]*>\s*)+)<\/span>/g;
          //                         let result = xmlString;
          //                         let previous;

          //                         do {
          //                             previous = result;
          //                             result = result.replace(regex, '<p>$1</p>');
          //                         } while (result !== previous);

          //                         return result;
          //                     };
          //                     html = replaceSpanWithP(html);
          //                     console.log('rtfImageData.length');
          //                     // 执行替换：将html内容中的img标签的src替换成ref中的图片数据，如果上面上传了则为图片路径
          //                     html = this.replaceImagesFileSourceWithInlineRepresentation(
          //                         html,
          //                         imgSrcs,
          //                         imgCosUrls
          //                     );
          //                     console.log('replaceImagesFileSourceWithInlineRepresentation', html);
          //                     editor.dangerouslyInsertHtml(html);
          //                 };
          //                 rtfImageData.forEach((fileItem, fileIndex) => {
          //                     cos.upload(true, COS_BIZ_TYPE.DOC_UPLOAD, [fileItem]).then((res) => {
          //                         imgCosUrls.push({url: res.url, fileIndex});
          //                         if (imgCosUrls.length === rtfImageData.length) {
          //                             finishedUpload();
          //                         }
          //                     });
          //                 });
          //             }
          //         }

          //         // 阻止默认的粘贴行为
          //         event.preventDefault();
          //         // eslint-disable-next-line standard/no-callback-literal
          //         cb && cb(false); // 返回值（注意，vue 事件的返回值，不能用 return）
          //         return false;
          //     } else {
          //         // 返回 true ，继续默认的粘贴行为
          //         // eslint-disable-next-line standard/no-callback-literal
          //         cb && cb(true); // 返回值（注意，vue 事件的返回值，不能用 return）
          //         return true;
          //     }
          // }
      },
      /**
   * 从html代码中匹配返回图片标签img的属性src的值的集合
   * @param htmlData
   * @return Array
   */
      findAllImgSrcsFromHtml (htmlData) {
          const regex = /<img[^>]+src="([^">]+)"/g;
          const matches = htmlData.match(regex);
          const srcArr = matches ? matches.map(match => match.match(/src="([^">]+)"/)[1]) : [];
          return srcArr;
      },
      /**
   * 从rtf内容中匹配返回图片数据的集合
   * @param rtfData
   * @return Array
   */
      extractImageDataFromRtf (rtfData) {
          if (!rtfData) {
              return [];
          }

          const regexPictureHeader =
      /{\\pict[\s\S]+?({\\\*\\blipuid\s?[\da-fA-F]+)[\s}]*/;
          const regexPicture = new RegExp(
              '(?:(' + regexPictureHeader.source + '))([\\da-fA-F\\s]+)\\}',
              'g'
          );
          const images = rtfData.match(regexPicture);
          const result = [];

          if (images) {
              for (const image of images) {
                  let imageType = false;

                  if (image.includes('\\pngblip')) {
                      imageType = 'image/png';
                  } else if (image.includes('\\jpegblip')) {
                      imageType = 'image/jpeg';
                  }

                  if (imageType) {
                      const saveName = cos.reNameFile(20) + '.' + mimeToExtension[imageType];
                      // 开始上传逻辑
                      // const file = this.hexToFile(image, saveName, imageType);
                      const dataUrl = `data:${imageType};base64,${
                          this._convertHexToBase64(image
                              .replace(regexPictureHeader, '')
                              .replace(/[^\da-fA-F]/g, ''))}`;
                      const file = this.dataURLtoBlob(dataUrl);
                      result.push({
                          // hex: `data:${imageType};base64,${
                          //     this._convertHexToBase64(image
                          //         .replace(regexPictureHeader, '')
                          //         .replace(/[^\da-fA-F]/g, ''))}`,
                          saveName: saveName,
                          name: saveName,
                          data: file,
                          type: imageType
                      });
                  }
              }
          }

          return result;
      },
      dataURLtoBlob (dataurl) {
          const arr = dataurl.split(',');
          const mime = arr[0].match(/:(.*?);/)[1];
          const bstr = atob(arr[1]);
          let n = bstr.length;
          const u8arr = new Uint8Array(n);
          while (n--) {
              u8arr[n] = bstr.charCodeAt(n);
          }
          return new Blob([u8arr], { type: mime });
      },

      /**
       * base64转hex
       * @param hex          {String} hex十六进制
       * @param fileName     {String} 文件名
       * @param mimeType     {String} 文件类型
       * @returns hex        {String} hex十六进制
       */
      hexToFile (hexString, fileName, mimeType) {
          // 将十六进制字符串转成字节数组
          const bytes = hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16));
          // 从字节数组创建一个Blob对象
          const blob = new Blob([new Uint8Array(bytes)], { type: mimeType });
          // 从Blob创建一个File对象
          const file = new File([blob], fileName, { type: mimeType });
          return file;
      },
      /**
   * 将html内容中img标签的属性值替换
   * @param htmlData html内容
   * @param imageSrcs html中img的属性src的值的集合
   * @param imagesHexSources rtf中图片数据的集合，与html内容中的img标签对应
   * @return String
   */
      replaceImagesFileSourceWithInlineRepresentation (
          htmlData,
          imageSrcs,
          imgCosUrls
      ) {
          if (imageSrcs.length === imgCosUrls.length) {
              for (let i = 0; i < imageSrcs.length; i++) {
                  const findItem = imgCosUrls.find(img => img.fileIndex === i);
                  htmlData = htmlData.replace(new RegExp(imageSrcs[i], 'g'), findItem.url);
              }
          }

          return htmlData;
      },

      /**
   * 十六进制转base64
   */
      _convertHexToBase64 (hexString) {
          return btoa(
              hexString
                  .match(/\w{2}/g)
                  .map((char) => {
                      return String.fromCharCode(parseInt(char, 16));
                  })
                  .join('')
          );
      },
      /**
       * 自定义校验链接
       * 1. 返回 true ，说明检查通过，编辑器将正常插入链接
       * 2. 返回一个字符串，说明检查未通过，编辑器会阻止插入。会 alert 出错误信息（即返回的字符串）
       * 3. 返回 undefined（即没有任何返回），说明检查未通过，编辑器会阻止插入。但不会提示任何信息
       */
      checkLink (text, url) {
          if (!url.trim()) {
              return '请输入链接地址';
          }
          if (url.indexOf('http') !== 0) {
              return '链接必须以 http/https 开头';
          }
          return true;
      },
      // 返回值有三种选择：
      // 1. 返回 true ，说明检查通过，编辑器将正常插入图片
      // 2. 返回一个字符串，说明检查未通过，编辑器会阻止插入。会 alert 出错误信息（即返回的字符串）
      // 3. 返回 undefined（即没有任何返回），说明检查未通过，编辑器会阻止插入。但不会提示任何信息
      checkImage (src) {
          if (!src.trim()) {
              return '请输入图片地址';
          }
          if (src.indexOf('http') !== 0) {
              return '图片网址必须以 http/https 开头';
          }
          return true;
      }
  },
  beforeDestroy () {
      const editor = this.editor;
      if (editor == null) return;
      editor.destroy();
  }
};

</script>
<!-- <style src="@wangeditor/editor/dist/css/style.css"></style> -->
<style lang="less" scoped>
.qa-editor {
  width: 100%;
  text-align: left;

&__toolbar {
  border-bottom: 1px solid rgba(17,32,70,.13);
}
&__editor {
  width: 100%;
  height: calc(100% - 41px);
  font-size: 15px
}
/deep/ .w-e-modal {
  z-index: 10000;

  .babel-container:nth-child(3) {
     display: none;
  }
}
/deep/ .w-e-text-placeholder {
  color: var(--color-text-caption);
  white-space: pre-wrap;
  word-wrap: break-word;
  font-style: normal;
}
  /deep/ .w-e-bar {
      background-color: #fff;
  }

  /deep/ .w-e-text-container {
      background-color: transparent;
      img {
          max-width: 300px;
          min-height: 24px;
          min-width: 24px;
          max-height: 300px;
      }
  }
}
</style>
